package serviceimpl;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import domain.GrashBean;
import domain.Tax;
import lib.JsonHelper;
import lib.MySQLLoaclHelper;
import service.ws.BareResponseProcessor;
import service.ws.CommonWSHandler;
import service.ws.WSHandler;

public class Iqiyi extends GraspBase {
	private String url = "http://www.iqiyi.com/dianying_new/i_list_haolaiwu.html";//好莱坞
	@SuppressWarnings("rawtypes")
	public void getHtml() throws Exception{
		WSHandler handler = new CommonWSHandler(url);
		handler.get();
		HttpResponse resp = handler.process(BareResponseProcessor.getInstance());
		Document doc = Jsoup.parseBodyFragment(EntityUtils.toString(resp.getEntity()));
		Element body = doc.body();
		Elements eles = body.getElementsByClass("J_videoLi");
		List<GrashBean> iqiyiBeans = new ArrayList<>();
		for (Element ele : eles) {
			System.out.println(ele);
			GrashBean iqiyiBean = new GrashBean();
			Element aHref = ele.select("[href]").get(1);
			String name = aHref.text();
			iqiyiBean.post_title = name;
			iqiyiBean.post_name = URLEncoder.encode(name, "UTF-8");
			List<Map> find = MySQLLoaclHelper.find("select * from wp_posts where post_name=?",iqiyiBean.post_name);
			if(find.size()==0){
				iqiyiBean.filmname = name;
				iqiyiBean.clarity = "高清";
				iqiyiBean.button2 = "百度网盘";
				iqiyiBean.keywords = String.format("%1$s百度云,%1$s高清下载,%1$s网盘,%1$s下载,%1$s电影", name);
				//去详情页那数据
				String url = aHref.attr("href");
				Document detailDoc = Jsoup.parse(new URL(url), 10000);
				Elements progInfos = detailDoc.getElementsByClass("progInfo_txt");
				if(progInfos.size()==0) {
					continue;
				}
				Elements types = progInfos.get(0).getElementsByClass("type-con");
				Element type1 = types.get(1);
				Element type2 = types.get(2);
				Element type4 = types.get(4);
				Elements type1Eles = type1.select("[href]");//导演
				Elements type2Eles = type2.select("[href]");//演员
				List<Tax> taxs = new ArrayList<>();
				String director = type1Eles.get(0).text();
				for (Element type : type1Eles) {
					Tax tax = new Tax();
					tax.name = type.text();
					tax.taxonomy = "director";
					tax.sulg = URLEncoder.encode(type.text(),"UTF-8");
					taxs.add(tax);
				}
				for (Element type : type2Eles) {
					Tax tax = new Tax();
					tax.name = type.text();
					tax.taxonomy = "performer";
					tax.sulg = URLEncoder.encode(type.text(),"UTF-8");
					taxs.add(tax);
				}
				
				String text4Str = type4.text();
				String[] text4s = text4Str.split("。");
				String post_content = "";
				int index = 1;
				for (int i = 0; i < text4s.length; i++) {
					post_content += String.format("%s%s", text4s[i],"。");
					if(post_content.length()>=100*index) {
						post_content = String.format("%s%s", post_content,"\n\r");
						index++;
					}
				}
				iqiyiBean.post_content = post_content;
				Date date =  new Date();
				//时光网电影搜索接口http://service-channel.mtime.com/Search.api?Ajax_CallBack=true&Ajax_CallBackType=Mtime.Channel.Services&Ajax_CallBackMethod=GetSuggestObjs&Ajax_CrossDomain=1&Ajax_RequestUrl=http://www.mtime.com/&t=1503676533224&Ajax_CallBackArgument0=f&Ajax_CallBackArgument1=290&Ajax_CallBackArgument2=1&_=1503676511004
				String mtimeUrl = String.format("http://service-channel.mtime.com/Search.api?Ajax_CallBack=true&Ajax_CallBackType=Mtime.Channel.Services&Ajax_CallBackMethod=GetSuggestObjs&Ajax_CrossDomain=1&Ajax_RequestUrl=http://www.mtime.com/&t=%s&Ajax_CallBackArgument0=%s&Ajax_CallBackArgument1=290&Ajax_CallBackArgument2=1&_=%s", date.getTime(),name,date.getTime());
				Response res = null;
				try {
					res = Jsoup.connect(mtimeUrl)
							.header("Accept", "*/*")
							.header("Accept-Encoding", "gzip, deflate")
							.header("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
							.header("Content-Type", "application/json;charset=UTF-8").ignoreContentType(true).execute();
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				
				String resbody = res.body();
				String resUrl = "";
				if(resbody.indexOf("[")!=-1 &&  resbody.lastIndexOf("]")!=-1) {
					String resarrayStr = resbody.substring(resbody.indexOf("["), resbody.lastIndexOf("]")+1);
					List<Map<String,String>> resList = JsonHelper.fromString(resarrayStr, List.class, Map.class);
					if(resList.size()>1) {
						for (Map<String, String> map : resList) {
							if(map.get("titlecn").equals(name) && map.get("director").equals(director)) {
								resUrl = map.get("moviepage");
								break;
							}
						}
					}else if(resList.size()==1){
						resUrl = resList.get(0).get("moviepage");
					}
				}
				if(StringUtils.isNoneBlank(resUrl)) {
					Element mtimeEle = Jsoup.parse(new URL(resUrl),10000).body();
					Elements runtimes = mtimeEle.select("[property=V:runtime]");
					Elements genres = mtimeEle.select("[property=v:genre]");//标签and分类
					Elements initialReleaseDates = mtimeEle.select("[property=v:initialReleaseDate]");//上映时间
					Elements baseInfos = mtimeEle.select("[pan=M14_Movie_Overview_BaseInfo]");
					Elements plotsSummarys = mtimeEle.select("[pan=M14_Movie_Overview_PlotsSummary]");
					String company = "";
					for (Element info : baseInfos) {
						if(info.select("strong").text().contains("编剧")) {
							int size = info.select("a").size()>2?2:1;
							iqiyiBean.screenwriter = StringUtils.join(info.select("a").subList(0, size).stream().map(Element :: text).collect(Collectors.toList()),"/");
						}else if(info.select("strong").text().contains("国家地区")) {
							String country = info.select("a").get(0).text();
							Tax tax = new Tax();
							tax.name = country;
							tax.taxonomy = "country";
							tax.sulg = URLEncoder.encode(country,"UTF-8");
							taxs.add(tax);
						}else if(info.select("strong").text().contains("发行公司")) {
							company = info.select("a").get(0).text();
						}else if(info.select("strong").text().contains("更多片名")) {
							iqiyiBean.filmname = String.format("%s/%s", iqiyiBean.filmname, StringUtils.join(info.select("span").stream().map(Element::text).collect(Collectors.toList()),"/"));
						}
					}
					iqiyiBean.post_content = String.format("%s\n\r发行公司：%s\n\r%s", iqiyiBean.post_content,company,plotsSummarys.select("p").get(0).text());
					if(runtimes.size()>0) {
						iqiyiBean.runtime = runtimes.get(0).text();
					}
					for (Element genre : genres) {
						Tax tax = new Tax();
						tax.name = genre.text();
						tax.taxonomy = "post_tag";
						tax.sulg = URLEncoder.encode(genre.text(),"UTF-8");
						taxs.add(tax);
					}
					if(initialReleaseDates.size()>0) {
						iqiyiBean.ontime = initialReleaseDates.get(0).text();
					}
				}
				iqiyiBean.taxs = new ArrayList<>(new HashSet<>(taxs));
				iqiyiBean.post_status = "draft";//草稿
				iqiyiBean.post_date = date;
//				iqiyiBean.post_date_gmt = date;
				iqiyiBean.post_author = 1;//作者
				iqiyiBean.comment_status = "open";//开启评论
				iqiyiBean.ping_status = "closed";
				iqiyiBean.post_modified = date;
//				iqiyiBean.post_modified_gmt = date;
				iqiyiBean.post_type = "post";
				iqiyiBeans.add(iqiyiBean);
				//开始入库
				insertDb(iqiyiBean,1);
			}
			Thread.sleep(10000);
		}
	}
}
